package com.adams.struts;

import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.FilterConfig;

import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.FilterDispatcher;

import com.adams.utils.ResourceUtil;

@SuppressWarnings(
{ "unchecked", "deprecation" })
public class AutoLoadConifgFilterDispatcher extends FilterDispatcher
{
	@Override
	protected Dispatcher createDispatcher(FilterConfig filterConfig)
	{
		Map<String, String> params = new HashMap<String, String>();

		for (Enumeration e = filterConfig.getInitParameterNames(); e
				.hasMoreElements();)
		{
			String name = (String) e.nextElement();
			String value = filterConfig.getInitParameter(name);
			params.put(name, value);
		}
		// 加载modules下的struts配置文件
		getStrutsConfig(params);
		return new Dispatcher(filterConfig.getServletContext(), params);
	}

	// 加载modules下的struts配置文件
	private void getStrutsConfig(Map<String, String> m)
	{
		String strutsPath = new String(
				"struts-default.xml,struts-plugin.xml,struts.xml");
		Set<String> xmls = ResourceUtil.getResources(ResourceUtil.ADAMS_PACK,
				"xml", true);
		for (String xml : xmls)
		{
			int pos = xml.indexOf(ResourceUtil.PACK_FILE_SEP + "struts-");
			if (pos != -1)
			{
				URL xmlUrl = Thread.currentThread().getContextClassLoader()
						.getResource(xml);
				if (null != xmlUrl)
				{
					strutsPath += "," + xml;
				}
			}

		}

		m.put("config", strutsPath);
	}

}
